package com.example.music.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;


/**
 * 接口文档配置---Swagger2
 * @author ZCL
 * @date 2021/12/21 14:21
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                /*Controller层的包地址*/
                .apis(RequestHandlerSelectors.basePackage("com.example.music.controller"))
                //任何路径都可以
                .paths(PathSelectors.any())
                .build()
                //设置Swagger
                .securitySchemes(securitySchemes())
                //
                .securityContexts(securityContexts());

    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                //标题
                .title("Now Moon 后台管理系统")
                //描述
                .description("这里是一个新音乐平台")
                .contact(new Contact("Melted","http:localhost:8088/doc.html","2476073514@qq.com"))
                .version("1.0")
                .build();

    }

    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> arrayList = new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
        arrayList.add(apiKey);
        return arrayList;
    }


    //需要认证的路径
    private List<SecurityContext> securityContexts(){
        //设置请求头信息
        List<SecurityContext> result = new ArrayList<>();
        boolean resultPath = result.add(getContextByPath());
        return result;

    }//像swagger添加全局授权
    private SecurityContext getContextByPath() {
        return SecurityContext.builder()
                .securityReferences(defaultPath())
                //.forPaths(PathSelectors.regex("/hello/.*"))
                .forPaths(PathSelectors.any())
                .build();

    }
    //像swagger添加全局授权
    private List<SecurityReference> defaultPath() {
        List<SecurityReference> list = new ArrayList<>();
        //授权范围--设置为全局
        AuthorizationScope scope = new AuthorizationScope("global","accessEverything");

        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = scope;
        list.add(new SecurityReference("Authorization",authorizationScopes));

        return list;
    }
}
